class Solution
{
    int m, n;
    bool check[7][7];
    int dx[4] = { 1,-1,0,0 };
    int dy[4] = { 0,0,1,-1 };
public:
    bool exist(vector<vector<char>>& board, string word)
    {
        m = board.size(), n = board[0].size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {
                    if (dfs(board, word, i, j, 0))
                        return true;
                }
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>>& board, string word, int i, int j, int pos)
    {
        if (pos == word.size() - 1)
        {
            return true;
        }
        check[i][j] = true;

        for (int k = 0; k < 4; k++)
        {
            int x = dx[k] + i;
            int y = dy[k] + j;

            if (x < m && y < n && x >= 0 && y >= 0 && check[x][y] == false && board[x][y] == word[pos + 1])
            {
                if (dfs(board, word, x, y, pos + 1))
                    return true;
            }
        }
        check[i][j] = false;
        return false;
    }
};